package cn.le.bean.util;

import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;

/**
 * 请求调用客户端
 * Created by zsq on 2017/8/2.
 */
public class RestfullClient {
    private static final Logger logger = LoggerFactory.getLogger(RestfullClient.class);
    private static final Charset UTF8 = Charset.forName("utf-8");
    private static final OkHttpClient client = new OkHttpClient();
    private static final MediaType json = MediaType.parse("application/json;charset=utf-8");

    public static String post(String url) {
        return post(url, null);
    }

    public static String post(String url, Map<String, Object> params) {
        StringBuilder result = new StringBuilder();
        BufferedInputStream bis = null;
        ByteArrayOutputStream bos = null;
        try {
            HttpURLConnection http = (HttpURLConnection) new URL(url).openConnection();
            // 提交模式
            http.setRequestMethod("POST");
            // 连接超时 单位毫秒
            http.setConnectTimeout(10000);
            // 读取超时 单位毫秒
            http.setReadTimeout(2000);
            // 发送POST请求必须设置如下两行
            http.setDoInput(true);
            http.setDoOutput(true);
            http.setRequestProperty("charset", "UTF-8");
            http.setRequestProperty("connection", "Keep-Alive");
            http.setRequestProperty("content-type", json.toString());
            // 发送请求参数，格式为JSON格式
            if (params != null) {
                // 获取URLConnection对象对应的输出流
                OutputStream os = http.getOutputStream();
                os.write(JSONObject.toJSONString(params).getBytes());
                // flush输出流的缓冲
                os.flush();
                os.close();
            }
            // 开始获取数据
            bos = new ByteArrayOutputStream();
            bis = new BufferedInputStream(http.getInputStream());
            int len;
            byte[] arr = new byte[1024];
            while ((len = bis.read(arr)) != -1) {
                bos.write(arr, 0, len);
                bos.flush();
            }
            result.append(bos.toString(UTF8.name()));
        } catch (Exception e) {
            logger.error(String.format("POST请求失败 : %s", url), e);
        } finally {
            try {
                bis.close();
                bos.close();
            } catch (Exception e) {
            }
        }
        return result.toString();
    }

    public static String okPost(String url, Map<String, Object> params) {
        try {
            RequestBody body = RequestBody.create(json, JSONObject.toJSONString(params));
            Request request = new Request.Builder().url(url).post(body).build();
            okhttp3.Response response = client.newCall(request).execute();
            return response.body().string();
        } catch (Exception e) {
            logger.error(String.format("POST请求失败 : %s", url), e);
        }
        return null;
    }

    public static okhttp3.Response okResponsePost(String url, Map<String, Object> params) {
        try {
            RequestBody body = RequestBody.create(json, JSONObject.toJSONString(params));
            Request request = new Request.Builder().url(url).post(body).build();
            return client.newCall(request).execute();
        } catch (Exception e) {
            logger.error(String.format("POST请求失败 : %s", url), e);
        }
        return null;
    }

    public static String okPost(String url, List params) {
        try {
            RequestBody body = RequestBody.create(json,JSONObject.toJSONString(params));
            Request request = new Request.Builder().url(url).post(body).build();
            okhttp3.Response response = client.newCall(request).execute();
            return response.body().string();
        } catch (Exception e) {
            logger.error(String.format("POST请求失败 : %s", url), e);
        }
        return null;
    }

    public static String okPost(String url, Map<String, Object> params, String token) {
        try {
            RequestBody body = RequestBody.create(json, JSONObject.toJSONString(params));
            Request request = new Request.Builder()
                    .addHeader("authorization", token)
                    .url(url).post(body).build();
            okhttp3.Response response = client.newCall(request).execute();
            return response.body().string();
        } catch (Exception e) {
            logger.error(String.format("POST请求失败 : %s", url), e);
        }
        return null;
    }

    public static String okPost(String url, String formatJson) {
        try {
            RequestBody body = RequestBody.create(json, formatJson);
            Request request = new Request.Builder().url(url).post(body).build();
            Response response = client.newCall(request).execute();
            return response.body().string();
        } catch (Exception e) {
            logger.error(String.format("POST请求失败 : %s", url), e);
        }
        return null;
    }
}
